<?php
include "../database/database.php";

$userid = $_GET['userid'];
$coupon_id = $_GET['coupon_id'];

$sql = "SELECT * FROM `mycoupon` WHERE `userid` = ${userid} AND `couponid` = ${coupon_id}";
$rows = $conn->query($sql)->fetch_assoc();
if ($rows['couponid'] == $coupon_id) {
	echo json_encode(array('code' => 300,'msg' => "已领取过"));
	exit;
}else{
	$sql = "UPDATE `coupon` SET `number` = `number` - 1 WHERE `couponid` = ${coupon_id}";
	$conn->query($sql);
	$affect = $conn->affected_rows;
	if ($affect) {
		$con_info = $conn->query("SELECT * FROM `coupon` WHERE `couponid` = ${coupon_id}")->fetch_assoc();
		$goods_id = $con_info['goodsid'];
		$price = $con_info['price'];

		$data = array(
			"userid"=>$userid,
			"couponid"=>$coupon_id,
			"goodsid"=>$goods_id,
			"price"=>$price,
		);

		$k = '`' . implode('`,`', array_keys($data)) . '`';
		$v = "'" . implode("','", $data) . "'";
		
		$sql = "INSERT INTO `mycoupon` ({$k}) VALUES ({$v})";

		$conn->query($sql);
		$affect = $conn->insert_id;

		if($affect){
			echo json_encode(array('code' => 200,'msg' => "领取成功"));
	        exit;
		}else{

			$sql = "UPDATE `coupon` SET `number` = `number` + 1 WHERE `couponid` = ${coupon_id}";
			$conn->query($sql);
			$affect = $conn->affected_rows;
		}
	}else{
		echo json_encode(array('code' => 400,'msg' => "领取优惠券时出错"));
	    exit;
	}
}







?>